#include "DataCent.h"
#include "StdSqlite3.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <openssl/sha.h>
#define  DBPath "./chatroom.db"

static SQL *s;

bool DataCenterInit()
{   
    s = StdSqlite3Init(DBPath);
    if(s == NULL)
    {
        return false;
    }

    char sql[] = "create table if not exists user(name text primary key,passwd text not null,salt text not null);";
    return SQLExec(s,sql);
}

bool IsUserExist(const char* name)
{
    char sql[1024] = {0};
    sprintf(sql,"select count(*) from user where name = '%s';",name);
    char **result = GetTableInfo(s,sql,NULL,NULL);
    if(result == NULL)
        return false;

    int count = atoi(result[1]);
    FreeTableInfo(result);
    return count != 0;
}

char *GenerateSlat()
{   
    srand(time(NULL));
    char salt[17] = {0};
    for(int i = 0;i < 16; i++)
    {
        salt[i] = 32 + rand() % 95;
    }
    return strdup(salt);
}

char* HashPasswd(const char*passwd,const char*salt)
{
    int newLen = strlen(passwd)+strlen(salt)+1;
    char* newPasswd = (char*)malloc(newLen);
    
    if(newPasswd == NULL)
    {
        printf("AddNewUser malloc error!\n");
        return NULL;
    }
    memset(newPasswd,0,newLen);
    strcat(newPasswd,passwd);
    strcat(newPasswd,salt);

    unsigned char hashPasswd[SHA256_DIGEST_LENGTH] = {0};
    SHA256(newPasswd,strlen(newPasswd),hashPasswd);

    char result[SHA256_DIGEST_LENGTH*2] = {0};
    for(int i = 0; i < SHA256_DIGEST_LENGTH;i++)
    {
        char temp[8] = {0};
        sprintf(temp,"%x",hashPasswd[i]);
        strcat(result,temp);
    }
    free(newPasswd);
    return strdup(result);
}

bool AddNewUser(const char *name, const char *passwd)
{   
    //生成随机颜值
    char *salt = GenerateSlat();
    char * result = HashPasswd(passwd,salt);
    char sql[1024] = {0};
    sprintf(sql,"insert into user values('%s','%s','%s');",name,result,salt);
    free(salt);
    free(result);
    return SQLExec(s,sql);
}

char*GetUserSalt(const char *name)
{ 
    char sql[1024] = {0};
    sprintf(sql,"select salt from user where name = '%s';",name);
    char **result = GetTableInfo(s,sql,NULL,NULL);
    if(result == NULL)
       return NULL;
    char *salt = strdup(result[1]);
    FreeTableInfo(result);
    return salt;
}
bool IsAccountEqual(const char *name, const char *passwd)
{   
    char sql[1024] = {0};
    char *salt = GetUserSalt(name);
    if(salt == NULL)
        return NULL;
    char *hashpasswd = HashPasswd(passwd,salt);
    sprintf(sql,"select count(*) from user where name = '%s' and passwd = '%s';",name,hashpasswd);
    free(hashpasswd);
    free(salt);
    char **result = GetTableInfo(s,sql,NULL,NULL);
    if(result == NULL)
        return false;

    int count = atoi(result[1]);
    FreeTableInfo(result);
    return count != 0;
    
}
